﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;

namespace OperateWebcam
{
    public class CVideo
    {
        private IntPtr lwndC;       //保存无符号句柄 
        private IntPtr mControlPtr; //保存管理指示器 
        private int mWidth; 
        private int mHeight; 
        public CVideo(IntPtr handle, int width, int height) 
        { 
            mControlPtr = handle; //显示视频控件的句柄 
            mWidth = width;      //视频宽度 
            mHeight = height;    //视频高度 
        } 
        /// <summary> 
        /// 打开视频设备 
        /// </summary> 
        public void StartWebCam() 
        { 
            byte[] lpszName = new byte[100]; 
            byte[] lpszVer = new byte[100];
            // string webcamname = "Altair USB2.0 Camera";
            // VideoAPI.capGetDriverDescriptionA(1, lpszName, 100, lpszVer, 100);
            this.lwndC = VideoAPI.capCreateCaptureWindowA(lpszName, VideoAPI.WS_CHILD | VideoAPI.WS_VISIBLE, 0, 0, mWidth, mHeight, mControlPtr, 0);
            if(VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_DRIVER_CONNECT, (short)0, 0))
            {
                VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SET_PREVIEWRATE, 100, 0);
                VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SET_PREVIEW, true, 0);
                //MessageBox.Show(s.ToString());
            }
            else
            {
                MessageBox.Show("ddqre");
            }
  
        } 
        /// <summary> 
        /// 关闭视频设备 
        /// </summary> 
        public void CloseWebcam() 
        { 
            VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_DRIVER_DISCONNECT, 0, 0); 
        } 
        ///   <summary>    
        ///   拍照 
        ///   </summary>    
        ///   <param   name="path">要保存bmp文件的路径 </param>    
        public void GrabImage(string path) 
        { 
            /*
            VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_EDIT_COPY, 0, 0);
            IDataObject obj1 = Clipboard.GetDataObject();
            if (obj1.GetDataPresent(typeof(Bitmap)))
            {
                Image image1 = (Image)obj1.GetData(typeof(Bitmap));
                image1.Save(path, ImageFormat.Jpeg);
            }*/// 从剪贴板存储,下面两行直接存储

            IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
            VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SAVEDIB, 0, hBmp.ToInt32());
        }
        /// <summary>
        /// 返回抓取图像
        /// </summary>
        /// <returns>抓取的图像</returns>
        public Bitmap GrabImage()
        {
            VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_EDIT_COPY, 0, 0);
            IDataObject obj1 = Clipboard.GetDataObject();
            Bitmap mybitmap = (Bitmap)obj1.GetData(typeof(Bitmap));
            return mybitmap;

        }
    } 
    
}
